package org.linphone.activity;

/*
 ChatListFragment.java
 Copyright (C) 2012  Belledonne Communications, Grenoble, France

 This program is free software; you can redistribute it and/or
 modify it under the terms of the GNU General Public License
 as published by the Free Software Foundation; either version 2
 of the License, or (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 */
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONObject;
import org.json.JSONTokener;
import com.leehuubsd.yiyanzb.R;
import org.linphone.core.LinphoneAddress;
import org.linphone.core.LinphoneChatMessage;
import org.linphone.core.LinphoneChatRoom;
import org.linphone.core.LinphoneCoreException;
import org.linphone.core.LinphoneCoreFactory;
import org.linphone.mediastream.Log;

import com.android.volley.AuthFailureError;
import com.android.volley.Request.Method;
import com.android.volley.RequestQueue;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.support.v4.app.Fragment;
import android.text.TextUtils;
import android.util.Base64;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * @author Sylvain Berfini
 */
public class RechargeFragment extends Fragment implements OnClickListener {
	static ProgressDialog m_Dialog;
	private EditText Unametext, Upwtext;
	// private String Uphone, Upwd;
	private EditText accounts, name, word;
	private LinearLayout loading;
	private String cardAmt, FrpId, account, cardno, cardpassword;
	private Button button;
	private TextView tv;
	private String str, s;
	private String OEMID, http;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.old_home_web, container, false);
		OEMID = getResources().getString(R.string.oem);
		http = getResources().getString(R.string.http);
		find(view);
		return view;
	}

	private void find(View v) {
		tv = (TextView) v.findViewById(R.id.cjwt_tv);
		accounts = (EditText) v.findViewById(R.id.charge_do_textview);
		name = (EditText) v.findViewById(R.id.editText1);
		word = (EditText) v.findViewById(R.id.EditText02);
		loading = (LinearLayout) v.findViewById(R.id.login_task_loading);
		button = (Button) v.findViewById(R.id.button1);
		button.setOnClickListener(this);
		tv.getPaint().setFlags(Paint.UNDERLINE_TEXT_FLAG);// 下划线
		tv.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				Intent intent3 = new Intent(getActivity(),
						WebsiteActivity.class);
				intent3.putExtra("pathweb",
						"http://faqbosideng.leehuu.cn/index-common.html");
				intent3.putExtra("title", "常见问题");
				startActivity(intent3);
			}
		});

	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.button1:
			cardno = name.getText().toString();
			cardpassword = word.getText().toString();
			if (accounts.getText().length() == 0) {
				account = str;
			} else {
				account = accounts.getText().toString();
			}

			if (!TextUtils.isEmpty(account) && !TextUtils.isEmpty(cardno)
					&& !TextUtils.isEmpty(cardpassword)) {
				button.setEnabled(false);
				loading.setVisibility(View.VISIBLE);

				m_Dialog = ProgressDialog
						.show(getActivity(), "", "请稍后……", true);
				m_Dialog.setIcon(android.R.drawable.ic_lock_idle_alarm);
				postDataToNe("/YXBp/dm9zb2Vt/VXNlUHJlcGFpZENhcmQy", account,
						cardno, cardpassword);
			} else {
				Toast.makeText(getActivity(), "输入有误,请重新输入!", Toast.LENGTH_SHORT)
						.show();
			}
			break;
		default:
			break;
		}
	}

	public void Show_Toast(String str) {
		Toast.makeText(getActivity(), str, Toast.LENGTH_SHORT).show();
	}

	/**
	 * post请求
	 * 
	 * @author li Feb 4, 2015
	 */
	private void postDataToNe(String path, final String Phone,
			final String cardNumber, final String cardPassword) {
		RequestQueue queue = Volley.newRequestQueue(getActivity());
		StringRequest request = new StringRequest(Method.POST, http + path,
				new Listener<String>() {
					@Override
					public void onResponse(String response) {

						m_Dialog.dismiss();
						Log.i("LOL", response);
						parserToObject(response);
						if ("0".equals(s)) {
							Toast.makeText(getActivity(), "充值成功", 0).show();
						} else {
						}
						button.setEnabled(true);
						loading.setVisibility(View.GONE);

					}
				}, new ErrorListener() {
					@Override
					public void onErrorResponse(VolleyError arg0) {

						m_Dialog.dismiss();
						Log.i("LOG", "!!!!onErrorResponse：" + arg0.toString());
						Toast.makeText(getActivity(), "获取数据失败，请稍后再试", 0).show();
						loading.setVisibility(View.GONE);
						button.setEnabled(true);
					}
				}) {
			protected Map<String, String> getParams() throws AuthFailureError {
				String p = encryptBASE64(Phone);
				Map<String, String> map = new HashMap<String, String>();
				map.put("dXNlck5hbWUPQ", p);
				map.put("cardNumber", cardNumber);
				map.put("cardPassword", cardPassword);
				map.put("proxyId", OEMID);
				return map;
			}
		};
		queue.add(request);
	}

	// json解析
	protected String parserToObject(String json) {
		JSONObject object;
		JSONTokener jsonTokener = new JSONTokener(json);
		try {
			JSONObject person = (JSONObject) jsonTokener.nextValue();
			int i = person.getInt("retCode");
			if (i == 0) {
				s = "0";
			} else {
				s = person.getString("exception");
				Toast.makeText(getActivity(),
						s + "(" + person.getInt("retCode") + ")",
						Toast.LENGTH_SHORT).show();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			Toast.makeText(getActivity(), "服务器异常！", Toast.LENGTH_SHORT).show();
			e.printStackTrace();
		}
		return s;
	}

	/**
	 * BASE64 加密
	 * 
	 * @param str
	 * @return
	 */
	@SuppressLint("NewApi")
	public String encryptBASE64(String str) {
		if (str == null || str.length() == 0) {
			return null;
		}
		try {
			byte[] encode = str.getBytes("UTF-8");
			// base64 加密

			String s = new String(Base64.encode(encode, 0, encode.length,
					Base64.DEFAULT), "UTF-8");
			String s1 = s.replaceAll("=", "PQ");
			Log.i("LOL", s1);
			return s1;
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		return null;
	}

}
